var pathname = window.location.pathname.split(".")[0];
var token,goUrl;//当前token 当前跳转登录页面地址
var user_login_message = '';//用户登录信息
var token_time;//登录时间
var expiration_time = 11.8 * 60 * 60 * 1000;//过期时间
// 获取是否分销商和上级ID
var {is_distributor,pid,is_branch_office_manage,is_branch_office_pitcher} = JSON.parse(localStorage.getItem('user_message')) ?? {is_distributor:0,pid:'',is_branch_office_manage:0,is_branch_office_pitcher:0};
var adminMessage = JSON.parse(localStorage.getItem('adminMessage'));
var cpsMessage = JSON.parse(localStorage.getItem('cpsMessage'));

if (pathname.indexOf('admin') != -1) {
    token = localStorage.getItem("adminToken");
    goUrl = '/admin/login/index';
    user_login_message = localStorage.getItem("adminMessage");
    token_time = JSON.parse(user_login_message)?.token_time
} else {
    token = localStorage.getItem("cpsToken");
    goUrl = '/cps/login/index';
    user_login_message = localStorage.getItem("cpsMessage");
    token_time = JSON.parse(user_login_message)?.token_time
}

$(function(){
    //加载弹出层
    layui.use(['form','element'],function() {
        layer = layui.layer;
        element = layui.element;
        element.on('tab(xbs_tab)', function(){
            let activeIndex = 0;
            let tab_id = $(this).attr('lay-id')
            $('dd').each((index,item)=>{
                if($(item).attr('tab-id') == tab_id){
                    $(item).addClass('layui-this')
                    activeIndex = $(item).parent().parent().index()
                }else{
                    $(item).removeClass('layui-this')
                }
            })
            $('.left_nav_tree').children().eq(activeIndex).addClass('layui-nav-itemed').siblings().removeClass('layui-nav-itemed')
        });
    });


    //触发事件
    var tab = {
        tabAdd: function (title, url, id) {
            if(new Date().getTime() >= token_time+expiration_time){
                jumpUrl(goUrl,true)
                return
            }
            url + "?token=" + token;
            //新增一个Tab项
            element.tabAdd("xbs_tab", {
                title: title,
                content:
                    '<iframe tab-id="' +
                    id +
                    '" frameborder="0" src="' +
                    url +
                    '" scrolling="yes" class="x-iframe"></iframe>',
                id: id,
            });
        },
        tabDelete: function (othis) {
            //删除指定Tab项
            element.tabDelete("xbs_tab", "44"); //删除：“商品管理”

            othis.addClass("layui-btn-disabled");
        },
        tabChange: function (id) {
            //切换到指定Tab项
            element.tabChange("xbs_tab", id); //切换到：用户管理
        },
    };
        

    $('.container .left_open i').click(function(event) {
        if($('.left-nav').css('left')=='0px'){
            $('.left-nav').animate({left: '-200px'}, 100);
            $('.page-content').animate({left: '0px'}, 100);
            $('.page-content-bg').hide();
        }else{
            $('.left-nav').animate({left: '0px'}, 100);
            $('.page-content').animate({left: '200px'}, 100);
            if($(window).width()<768){
                $('.page-content-bg').show();
            }
        }

    }); 

    $('.page-content-bg').click(function(event) {
        $('.left-nav').animate({left: '-221px'}, 100);
        $('.page-content').animate({left: '0px'}, 100);
        $(this).hide();
    });

    $('.layui-tab-close').click(function(event) {
        $('.layui-tab-title li').eq(0).find('i').remove();
    });

    $("tbody.x-cate tr[fid!='0']").hide();
    // 栏目多级显示效果
    $('.x-show').click(function () {
        if($(this).attr('status')=='true'){
            $(this).html('&#xe625;'); 
            $(this).attr('status','false');
            cateId = $(this).parents('tr').attr('cate-id');
            $("tbody tr[fid="+cateId+"]").show();
        }else{
            cateIds = [];
            $(this).html('&#xe623;');
            $(this).attr('status','true');
            cateId = $(this).parents('tr').attr('cate-id');
            getCateId(cateId);
            for (var i in cateIds) {
                $("tbody tr[cate-id="+cateIds[i]+"]").hide().find('.x-show').html('&#xe623;').attr('status','true');
            }
        }
    })

    //左侧菜单效果
    // $('#content').bind("click",function(event){
    $('.left-nav #nav li').click(function (event) {
        if($(this).children('.sub-menu').length){
            if($(this).hasClass('open')){
                $(this).removeClass('open');
                $(this).find('.nav_right').html('&#xe697;');
                $(this).children('.sub-menu').stop().slideUp();
                $(this).siblings().children('.sub-menu').slideUp();
            }else{
                $(this).addClass('open');
                $(this).children('a').find('.nav_right').html('&#xe6a6;');
                $(this).children('.sub-menu').stop().slideDown();
                $(this).siblings().children('.sub-menu').stop().slideUp();
                $(this).siblings().find('.nav_right').html('&#xe697;');
                $(this).siblings().removeClass('open');
            }
        }else{
            var url = $(this).children('a').attr('_href');
            var title = $(this).find('cite').html();
            var index  = $('.left-nav #nav li').index($(this));

            for (var i = 0; i <$('.x-iframe').length; i++) {
                if($('.x-iframe').eq(i).attr('tab-id')==index+1){
                    tab.tabChange(index+1);
                    event.stopPropagation();
                    return;
                }
            };
            
            tab.tabAdd(title,url,index+1);
            tab.tabChange(index+1);
        }
        
        event.stopPropagation();
         
    })


    $('.layui-nav dd').click(function (event) {
        $(this).parent().parent().siblings().removeClass('layui-nav-itemed')
        var url = $(this).children('a').attr('_href');
        var title = $(this).children('a').html();
        var index  = $(this).attr('tab-id')

        for (var i = 0; i <$('.x-iframe').length; i++) {
            if($('.x-iframe').eq(i).attr('tab-id')==index){
                tab.tabChange(index);
                event.stopPropagation();
                return;
            }
        };
        tab.tabAdd(title,url+'?token='+token,index);
        tab.tabChange(index);
        
        event.stopPropagation();
            
    })

    $('#reload').on('click',function(){
        if(new Date().getTime() >= token_time+expiration_time){
            jumpUrl(goUrl,true)
            return
        }else{
            location.replace(location.href);
        }
    })
})

var cateIds = [];
function getCateId(cateId) {
    
    $("tbody tr[fid="+cateId+"]").each(function(index, el) {
        id = $(el).attr('cate-id');
        cateIds.push(id);
        getCateId(id);
    });
}

// 获取当前设备类型
var os = function (){
    var ua = navigator.userAgent,
    isWindowsPhone = /(?:Windows Phone)/.test(ua),
    isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
    isAndroid = /(?:Android)/.test(ua),
    isFireFox = /(?:Firefox)/.test(ua),
    isChrome = /(?:Chrome|CriOS)/.test(ua),
    isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)),
    isPhone = /(?:iPhone)/.test(ua) && !isTablet,
    isPc = !isPhone && !isAndroid && !isSymbian;
    return {
        isTablet: isTablet,
        isPhone: isPhone,
        isAndroid: isAndroid,
        isPc: isPc
    };
}();
  
    

/*弹出层*/
/*
    参数解释：
    title   标题
    url     请求的url
    id      需要操作的数据id
    w       弹出层宽度（缺省调默认值）
    h       弹出层高度（缺省调默认值）
*/
function x_admin_show(title,url,w,h,btn=['保存', '关闭']){
    if(typeof w != 'string'){
        w = w + 'px'
    }
    if(typeof h != 'string'){
        h = h + 'px'
    }
    if (os.isAndroid || os.isPhone) {
        w = '90%';
        h = '90%';
    }
    if (title == null || title == '') {
        title=false;
    };
    if (w == null || w == '') {
        w=($(window).width()*0.9);
    };
    if (h == null || h == '') {
        h=($(window).height() - 50);
    };
    if(url.split('?').length == 1){
        url = url + `?token=${token}`
    }else{
        url = url + `&token=${token}`
    }
    if(new Date().getTime() >= token_time+expiration_time){
        jumpUrl(goUrl,true)
        return
    }
    layer.open({
        type: 2,
        area: [w, h],
        fix: false, //不固定
        maxmin: true,
        shadeClose: true,
        shade:0.4,
        title: title,
        content: url,
        btn,
        yes: function(){
            let iframes = $('iframe')[0].contentWindow.document.body
            $(iframes).find('#submitData').trigger('click'); 
        }
        ,btn2: function(){
            layer.closeAll();
        }
    });
}

/*关闭弹出框口*/
function x_admin_close(){
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

function x_admin_father_reload(){
    parent.location.reload();
}

/* 
    elem:upload上传按钮dom元素
    multiple:是否多选
    tokenUrl:oss授权验证接口地址
    client:oss方法 参数
    uploadElem:点击上传按钮dom元素
    chooseCallback:选择图片后的回调
    beforeUploadCallback:上传前的操作
    uploadSuccessCallback:上传成功的操作
    uploadErrorCallback:上传失败的操作
*/
function uploadFile(params){
    let { elem,uploadElem,chooseCallback,beforeUploadCallback,uploadSuccessCallback,uploadErrorCallback,multiple=false,ossUrl,accept='images',acceptMime='image/*' } = params
    let oss = ossUrl ?? '/admin/Uploads/uploadCredentials';
    var layerMask;
    layui.use(['layer', 'element', 'form', 'upload'], function () {
        var upload = layui.upload,client,files;
        var init = new Promise((resolve,reject)=>{
            // 请求oss sts临时授权接口
            Ajax(oss,{}).then(data =>{
                client = new OSS({
                    accessKeyId: data.data.accessKeyId,
                    accessKeySecret: data.data.accessKeySecret,
                    stsToken: data.data.securityToken,
                    bucket: data.data.bucket,
                    region: data.data.region
                })
                resolve()
            })
        });
        init.then(()=>{
            // 调用layui上传
            upload.render({
                elem,
                multiple,
                acceptMime,
                accept,
                auto:false,
                choose: function (obj) {
                    files = obj.pushFile();
                    chooseCallback ? chooseCallback() : '';//选择文件后的操作
                    if(!uploadElem){//如果没有全部上传按钮，则直接调用上传接口
                        allUpload()
                    }
                },
            })
            // 如果有全部上传接口,调用上传接口
            if(uploadElem){
                $(uploadElem).click(function(){
                    allUpload()
                }) 
            }
        });
        // 全部上传
        function allUpload(){
            let arrFiles = Object.values(files);
            let arrFilesIndex = Object.keys(files);
            layerMask = layer.load(1, {
                shade: [0.4,'#000']
            });
            if(accept == 'images'){
                if(arrFiles[0].size > 5 * 1024 * 1024){
                    layer.msg('超过图片最大限制5MB~', {icon: 5});
                    layer.close(layerMask)
                    delete files[arrFilesIndex[0]];
                    return false;
                }
            }
            for (let i in arrFiles) {
                uploadOssPut(arrFiles[i].name, arrFiles[i],arrFilesIndex[i]);
            }
        }
        // 上传文件到oss
        function uploadOssPut(name, file,fileIndex) {
            beforeUploadCallback ? beforeUploadCallback() : '';//上传前的操作
            client.put(fileName(name),file).then(function (v) {
                layer.close(layerMask)
                if (v.res.status === 200) { //上传成功
                    uploadSuccessCallback ? uploadSuccessCallback(v,name) : '';//上传成功的操作
                    delete files[fileIndex];
                    return false;
                } else {
                    uploadErrorCallback ? uploadErrorCallback() : '';//上传失败的操作
                }
            })
        }  
    })
}
/* 
    批量上传
    elem:upload上传按钮dom元素
    multiple:是否多选
    tokenUrl:oss授权验证接口地址
    client:oss方法 参数
    chooseCallback:选择图片后的回调
    beforeUploadCallback:上传前的操作
    uploadSuccessCallback:上传成功的操作
    uploadErrorCallback:上传失败的操作
*/
function batchUploadFile(params){
    let { elem,chooseCallback,beforeUploadCallback,uploadSuccessCallback,uploadErrorCallback,ossUrl,accept='images',acceptMime='image/*' } = params
    let oss = ossUrl ?? '/admin/Uploads/uploadCredentials';
    var layerMask;
    layui.use(['layer', 'element', 'form', 'upload'], function () {
        var upload = layui.upload,client,files;
        var init = new Promise((resolve,reject)=>{
            // 请求oss sts临时授权接口
            Ajax(oss,{}).then(data =>{
                client = new OSS({
                    accessKeyId: data.data.accessKeyId,
                    accessKeySecret: data.data.accessKeySecret,
                    stsToken: data.data.securityToken,
                    bucket: data.data.bucket,
                    region: data.data.region
                })
                resolve()
            })
        });
        init.then(()=>{
            // 调用layui上传
            upload.render({
                elem,
                multiple:true,
                acceptMime,
                accept,
                auto:false,
                choose: function (obj) {
                    files = obj.pushFile();
                    chooseCallback ? chooseCallback() : '';//选择文件后的操作
                    allUpload()
                },
            })
        });
        // 全部上传
        function allUpload(){
            let arrFiles = Object.values(files);
            let arrFilesIndex = Object.keys(files);
            layerMask = layer.load(1, {
                shade: [0.4,'#000']
            });
            for (let i in arrFiles) {
                uploadOssPut(arrFiles[i].name, arrFiles[i],arrFilesIndex[i],arrFilesIndex);
            }
        }
        let arrIndex = 0
        // 上传文件到oss
        function uploadOssPut(name, file,fileIndex,arrFilesIndex) {
            beforeUploadCallback ? beforeUploadCallback() : '';//上传前的操作
            client.put(fileName(name),file).then(function (v) {
                if (v.res.status === 200) { //上传成功
                    arrIndex++
                    if(arrFilesIndex.length === arrIndex){
                        uploadSuccessCallback ? uploadSuccessCallback(v,name,true) : '';//上传成功的操作
                        layer.close(layerMask)
                        arrIndex = 0
                    }else{
                        uploadSuccessCallback ? uploadSuccessCallback(v,name,false) : '';//上传成功的操作
                    }
                    
                    delete files[fileIndex];
                    return false;
                } else {
                    uploadErrorCallback ? uploadErrorCallback() : '';//上传失败的操作
                }
            })
        }  
    })
}
//文件上传路径+文件名
function fileName(name){
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth()+1;
    let day = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();
    return `${year}-${month}-${day}/${hour}-${minute}-${second}-${name}`;
}


layui.config({
    base: '/admin/xadmin/lib/layui/'
}).extend({
    selectN:'selectN',
})
layui.config({
    base: '/admin/xadmin/lib/layui/'
}).extend({
    selectM:'selectM',
})
layui.config({
    base: '/admin/xadmin/lib/layui/'
}).extend({
    inputTag:'inputTag',
})
// 自定义模块，这里只需要开放soulTable即可
layui.config({
    base: '/admin/xadmin/lib/layui/',   // 第三方模块所在目录
    version: 'v1.6.4' // 插件版本号
}).extend({                         
    soulTable: 'soulTable/soulTable',
    tableChild: 'soulTable/tableChild',
    tableMerge: 'soulTable/tableMerge',
    tableFilter: 'soulTable/tableFilter',
    excel: 'soulTable/excel',
});
// 单选
function selectN(params){
    let {url,selected,tips,name,field_id,field_Name,extraData=[],elem,loading=false,search=true,disabled,verify=''} = params
    
    layui.use(['selectN'], function () {
        $ = layui.jquery;
        var selectN = layui.selectN;
        var layerMaskSelectN;
        if(loading){
            layerMaskSelectN = layer.load(1, {
                shade: [0.4,'#000']
            });
        }
        Ajax(url,{},'get').then(data =>{
            layer.close(layerMaskSelectN)
            
            if (data.code === 200) {
                selectN({
                    //元素容器【必填】
                    elem

                    //候选数据【必填】
                    ,data:extraData.concat(data.data)

                    //默认值
                    ,selected

                    ,tips

                    //input的name 不设置与选择器相同(去#.)
                    ,name

                    //候选项数据的键名
                    ,field: {idName:field_id,titleName:field_Name}
                    ,search
                    ,disabled
                    ,verify
                });
            }
        });
    });
}
// 多选
function selectM(params){
    let {url,elem,selected,tips,name,field_id,field_Name,max,extraData=[]} = params
    
    layui.use(['selectM'], function () {
        $ = layui.jquery;
        var selectM = layui.selectM
        Ajax(url,{},'get').then(data =>{
            if (data.code === 200) {
                selectM({
                    //元素容器【必填】
                    elem

                    //候选数据【必填】
                    ,data:extraData.concat(data.data)

                    //默认值
                    ,selected

                    ,max

                    ,tips

                    //input的name 不设置与选择器相同(去#.)
                    ,name

                    //候选项数据的键名
                    ,field: {idName:field_id,titleName:field_Name}

                });
            }
        });
    });
}

// xmSelect
// https://maplemei.gitee.io/xm-select/#/component/install
function xmSelectA(option) {
    let {
        url,//请求地址
        initValue,//初始值
        initFn,//有初始值的操作
        el,//绑定的id
        color='#5fb878',//主题颜色
        pageSize=8,//分页条数
        paging=true,//分页开启
        direction='auto',//下拉方向
        prop={
            value:'id'
        },//自定义属性名称
        showCount=5,//展示在下拉框中的最多选项数量
        showIcon=true,//是否显示删除图标
        onFn,
        radio=false,//是否开启单选模式
        clickClose=false,//是否点击选项后自动关闭下拉框
        label={
            type: 'block',
            block: {
                //最大显示数量, 0:不限制
                showCount,
                //是否显示删除图标
                showIcon,
            }
        },
        icon='show',//单选需要隐藏图标
        disabled = false,//渲染禁用
        loading=false,
        isData=false,
        name,
        toolbar={
            show: true,
            list: ['ALL', 'REVERSE', 'CLEAR']
        },
	    pageRemote = true,
        remoteMethodFn,
    } = option
    var layerMaskXmSelect;
    if(loading){
        layerMaskXmSelect = layer.load(1, {
            shade: [0.4,'#000']
        });
    }
    if(remoteMethodFn){
        let option = {
            el,
            theme: {
                color,
            },
            name,
            autoRow: true,
            filterable: true,
            height: 'auto',
            pageSize,
            paging,
            pageRemote,
            direction,
            toolbar,
            prop,
            initValue,
            radio,
            clickClose,
            model: {
                icon,
                label
            },
            disabled,
            on: function (data) {
                if(onFn){
                    onFn(data)
                }
            },
            remoteMethod: function (val, cb, show, pageIndex) {
                if(remoteMethodFn){
                    remoteMethodFn(val, cb, show, pageIndex)
                }
            },
        }
        xmSelect.render(option)
    }else{
        Ajax(url).then(result => {
            layer.close(layerMaskXmSelect)
            if(initValue && initFn){
                initFn()
            }
            let option = {
                el,
                theme: {
                    color,
                },
                name,
                autoRow: true,
                filterable: true,
                height: 'auto',
                pageSize,
                paging,
                direction,
                toolbar,
                prop,
                initValue,
                data:isData ? result.data.data : result.data,
                radio,
                clickClose,
                model: {
                    icon,
                    label
                },
                disabled,
                on: function (data) {
                    if(onFn){
                        onFn(data)
                    }
                }
            }
            xmSelect.render(option)
        });
    }
}

// input 标签
// https://gitee.com/cshaptx4869/input-tag
function inputTag(option){
    let {elem,data,permanentData,onChange} = option
    layui.use(['inputTag'], function () {
        $ = layui.jquery;
        var inputTag = layui.inputTag
        var inputTags = inputTag.render({
            elem,
            data,//初始值
            permanentData,//不允许删除的值
            removeKeyNum: 8,//删除按键编号 默认，BackSpace 键
            createKeyNum: 13,//创建按键编号 默认，Enter 键
            beforeCreate:function(data, value){
                let values = formatValues(value).split(',');
                return getInclude(inputTags.getData(),values).toString();
            },
            onChange:function(data, value, type){
                onChange(data, value, type)
            }
        });
        // //清空数据方法
        // inputTags.clearData();
        // //获取数据方法
        // inputTags.getData();
    });
    function getInclude(arr1, arr2) {
        return arr2.filter((item) => {
            return !arr1.includes(item)
        })
    }
}

/* 
    tableList 表格列表
    elem:指定原始表格元素选择器（推荐id选择器）
    toolbar:开启表格头部工具栏区域
    url:数据接口
    id:表格id
    cols:表头
    page:分页
    limit:每页个数
*/
function tableList(params){
    $('.layui-form').find('button').each(function(index,item){
        if($(item).attr('lay-filter') == 'searchList'){
            $(item).attr('disabled',true)
            $(item).addClass('layui-btn-disabled')
            $(item).html('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>搜索')
        }
    })
    layui.use(['table',"form", "layer"], function () {
        let window_width = window.screen.width;
        let {
            elem,
            toolbar,
            url,
            id,
            cols,
            page = true,
            limit = 10,
            where={},
            fixWhere={},
            height,
            width,
            totalRow,
            done,
            parseData,
            customTotal,
            reset,
            initSort
        } = params;
        if(window_width > 1920){
            limit = limit + 5;
        }
        var table = layui.table
            form = layui.form,
            layer = layui.layer,
            lock = false;
        function customTotalFn(params){
            if(!lock){
                if(customTotal){
                    customTotal(params)
                }
                lock = true
            }
        }
        parseData = function(res){
            $('.layui-form').find('button').each(function(index,item){
                if($(item).attr('lay-filter') == 'searchList' ){
                    $(item).attr('disabled',false)
                    $(item).removeClass('layui-btn-disabled')
                    $('.layui-icon-loading').remove()
                }
            })
            if(params.parseData){
                return params.parseData(res)
            }else{
                customTotalFn(params.where)
                if(res.code == 200){
                    return {
                        "data": page ? res.data?.data ?? [] : res?.data ?? [], //解析数据列表
                        "code": res.code, //解析接口状态
                        'count':page ? res.data?.total ?? 0 : 0//解析数据长度
                    };
                }else{
                    layer.msg(res.message,{icon:5,time:1000});
                    return {
                        "data": [], //解析数据列表
                        "code": 200, //解析接口状态
                        'count':0//解析数据长度
                    };
                }
            }
        }
        //第一个实例
        table.render({
            elem
            , toolbar
            , url
            , id
            , cols
            , response: {
                statusCode: 200 //规定成功的状态码，默认：0
            }
            , headers:{
                token
            }
            , limit
            , page
            , where:{...where,...fixWhere}
            , height:os.isPc ? height : ''
            , width
            , totalRow
            , done
            , parseData
            , cellMinWidth:os.isPc ? 105 : 160
            , minWidth:os.isPc ? 105 : 160
            , initSort
        });
        form.on('submit(searchList)', function(data){
            params.where = {...data.field,...fixWhere}
            tableList(params)
            customTotalFn(params.where)
            return false
        });
        $('#resetList').on('click', function(){
            $(this).off('click')
            params.where = {}
            if(reset){
                reset()
            }
            customTotalFn(params.where)
            tableList(params)
        });
    });
}

// 获取单选的值 infoSelectN
function getSelectNValue(option,value){
    if($.isFunction(window.infoSelectN)){
        infoSelectN(option,value)
    }
    return {option,value}
}


function jumpUrl(url,isTop = false){
    if(isTop){
        top.location.href = url
    }else{
        location.href = url
    }
}
